var editRowsNumber,_datasDatagrid,selectForm,createDate1,createDate2,selectUsername,selectNickname,selectEmail,selectPhone,selectStatus;
var parentCenterTabs,dialogWeixinMsg,formWeixinMsg,id,sendMsg,msgType,content,mediaId,title,description,musicUrl,hQMusicUrl,thumbMediaId,weixinImageTextIds;

function addRow() {
	if (editRowsNumber != -1) {
		_datasDatagrid.datagrid('endEdit', editRowsNumber);
	} else {
		id.val(0);
		sendMsg.val('');
		content.val('');
		mediaId.val('');
		title.val('');
		description.val('');
		musicUrl.val('');
		hQMusicUrl.val('');
		thumbMediaId.val('');
		dialogWeixinMsg.dialog({title:'添加回复消息',iconCls:'icon-add',buttons:[{text:'添加',handler:dialogHandler}]});
		dialogWeixinMsg.dialog('open');
	}
}

function deleteRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确实要删除当前所有选择的记录吗？', function(b){
			if (b) {
				var ids = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
				}
				$.post(sy.bp()+"/admin/weixin/replyMsg/deletes", {ids:ids.join(",")}, function(data) {
					if (data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要删除的记录', 'error');
	}
}

function updateRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	switch (rows.length) {
	case 0:
		$.messager.alert('提示', '请选择要修改的记录', 'warning');
		break;
	case 1:
		if (editRowsNumber != -1) {
			_datasDatagrid.datagrid('endEdit', editRowsNumber);
		} else {
			var rowData = rows[0];
			id.val(rowData.id);
			msgType.combobox('setValue',rowData.msgType);
			sendMsg.val(rowData.sendMsg);
			content.val(rowData.content);
			mediaId.val(rowData.mediaId);
			title.val(rowData.title);
			description.val(rowData.description);
			musicUrl.val(rowData.musicUrl);
			hQMusicUrl.val(rowData.hQMusicUrl);
			thumbMediaId.val(rowData.thumbMediaId);
			dialogWeixinMsg.dialog({title:'更新回复消息',iconCls:'icon-add',buttons:[{text:'更新',handler:dialogHandler}]});
			dialogWeixinMsg.dialog('open');
		}
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，请每次修改一条记录', 'warning');
		break;
	}
}

function saveRow() {
	_datasDatagrid.datagrid('endEdit', editRowsNumber);
}

function rejectRow() {
	editRowsNumber = -1;
	_datasDatagrid.datagrid('rejectChanges');
	_datasDatagrid.datagrid('unselectAll');
}

function search_datas() {
	var formData = selectForm.form('getData', true);
	if(formData.createDate1 != '' && formData.createDate2 != '' && formData.createDate1 > formData.createDate2){
		$.messager.alert('提示', '开始时间不得大于结束时间，请重新选择！', 'warning');
	} else {
		if (selectForm.form('validate')) {
			_datasDatagrid.datagrid('load',sy.serializeObject(selectForm));
		}
	}
};

function dialogHandler() {
	//if (formWeixinMsg.form('validate')) {
		var url = sy.bp() + "/admin/weixin/replyMsg/";
		if (id.val() == '0') {
			url += "add";
		} else {
			url += "update";
		}
		$.post(url, $('#formWeixinMsg').serialize(), function(data) {
			if (data && data.result == 1) {
				dialogWeixinMsg.dialog('close');
				_datasDatagrid.datagrid('reload');
				$.messager.show({title:'系统提示',msg:'提交成功!',timeout:2000,showType:'slide'});
			} else {
				$.messager.alert('系统提示', data.msg);
			}
		}, "json");
	//}
}

$(function(){
	parentCenterTabs = parent.centerTabs;
	_datasDatagrid = $('#_datasDatagrid');
	editRowsNumber = -1;
	selectForm = $('#selectForm');
	var jsonArr;
//	= [
//       {value:'text',text:'文本类型'},{value:'image',text:'图片类型'},
//       {value:'voice',text:'语音类型'},{value:'video',text:'视频类型'},
//	   {value:'music',text:'音乐类型'},{value:'news',text:'图文类型'}
//	];
	var jsonArrStatus = [{value:0,text:'临时素材'},{value:1,text:'永久素材'}];
	dialogWeixinMsg = $('#dialogWeixinMsg').show().dialog({
		resizable : false,
		closed : true,
		closable : true,
		modal : true,
	});
	formWeixinMsg = $('#formWeixinMsg').form({});
	id = $('#id');
	
	
	sendMsg = $('#sendMsg').validatebox({required:true,validType:['maxLength[100]']});
	msgType = $('#msgType').combobox({required:true,editable:false,valueField:'code',textField:'name',
		url:sy.bp() + "/admin/dictionary/listDictionary?name=微信回复消息",
		onLoadSuccess : function(data) {
			     jsonArr = JSON.parse(JSON.stringify(data)); 
		},
		onChange:function(newValue, oldValue){
			if (newValue == 'image' || newValue == 'voice' || newValue == 'video') {
				mediaId.combogrid({
					url:sy.bp()+'/admin/weixin/material/list',
					queryParams:{type:msgType.combobox('getValue')}
				});
			}
			if (newValue == 'text') {
				$('#content1').show();
				$('#mediaId1').hide();
				$('#title1').hide();
				$('#description1').hide();
				$('#musicUrl1').hide();
				$('#hQMusicUrl1').hide();
				$('#thumbMediaId1').hide();
				$('#weixinImageTextIds1').hide();
			} else if (newValue == 'image' || newValue == 'voice') {
				$('#content1').hide();
				$('#mediaId1').show();
				$('#title1').hide();
				$('#description1').hide();
				$('#musicUrl1').hide();
				$('#hQMusicUrl1').hide();
				$('#thumbMediaId1').hide();
				$('#weixinImageTextIds1').hide();
			} else if (newValue == 'video') {
				$('#content1').hide();
				$('#mediaId1').show();
				$('#title1').show();
				$('#description1').show();
				$('#musicUrl1').hide();
				$('#hQMusicUrl1').hide();
				$('#thumbMediaId1').hide();
				$('#weixinImageTextIds1').hide();
			} else if (newValue == 'music') {
				$('#content1').hide();
				$('#mediaId1').hide();
				$('#title1').show();
				$('#description1').show();
				$('#musicUrl1').show();
				$('#hQMusicUrl1').show();
				$('#thumbMediaId1').show();
				$('#weixinImageTextIds1').hide();
			} else if (newValue == 'news') {
				$('#content1').hide();
				$('#mediaId1').hide();
				$('#title1').hide();
				$('#description1').hide();
				$('#musicUrl1').hide();
				$('#hQMusicUrl1').hide();
				$('#thumbMediaId1').hide();
				$('#weixinImageTextIds1').show();
			}
		}
	}).combobox('activeTextArrow').combobox('setValue', 'text');
	content = $('#content').validatebox({required:true,validType:['maxLength[1000]']});
	mediaId = $('#mediaId').combogrid({panelWidth:430,idField:'media_id',textField:'media',pagination:true,singleSelect:true,fitColumns:true,
		pageSize:10,pageList:[10,20,30,40,50],border:false,sortName:'id',sortOrder:'desc',view:sy.myview,emptyMsg:'没有查询到相关数据',
		columns:[[
		  {field:'id',hidden:true},
          {field:'media',title:'缩略图',width:50,formatter:function(value, row) {
        	  if (value) {
        		  return '<img src="'+sy.bp()+'/resources/upload/weixin/'+row.media+'" class="imgMaterial">'
        	  }
          }},
          {field:'status',title:'类型',width:100,
        	  formatter:function(value, row) {
	        		for ( var i = 0; i < jsonArrStatus.length; i++) {
						if (value == jsonArrStatus[i].value) {
							return jsonArrStatus[i].text;
						}
					}
	        	}
          },
          {field:'createTime',title:'上传时间',width:200},
          {field:'media_id',hidden:true}
        ]]  
	}).combogrid('activeTextArrow');
	title = $('#title').validatebox({required:true,validType:['maxLength[100]']});
	description = $('#description').validatebox({required:true,validType:['maxLength[200]']});
	musicUrl = $('#musicUrl').validatebox({required:true,validType:['maxLength[200]']});
	hQMusicUrl = $('#hQMusicUrl').validatebox({required:true,validType:['maxLength[200]']});
	thumbMediaId = $('#thumbMediaId').validatebox({required:true,validType:['maxLength[200]']});
	weixinImageTextIds = $('#weixinImageTextIds').combogrid({panelWidth:430,idField:'id',textField:'id',pagination:true,multiple:true,fitColumns:true,
		pageSize:10,pageList:[10,20,30,40,50],border:false,sortName:'id',sortOrder:'desc',view:sy.myview,emptyMsg:'没有查询到相关数据',url:sy.bp()+'/admin/weixin/imageTextMsg/list',
		columns:[[
		  {field:'id',hidden:true},
          {field:'title',title:'标题',align:'left',width:100,sortable:true},
          {field:'description',title:'描述',align:'left',width:100,sortable:true},
          {field:'picUrl',title:'图片链接',align:'left',width:100,sortable:true},
          {field:'url',title:'图文链接',align:'left',width:100,sortable:true}
        ]]  
	}).combogrid('activeTextArrow');
	
	_datasDatagrid.datagrid({
		url : sy.bp()+'/admin/weixin/replyMsg/list',
		fit : true,
		autoRowHeight : false,
		striped : true,
		rownumbers : true,
		pagination : true,
		singleSelect : false,
		fitColumns : true,
		pageSize : 10,
		pageList : [10,20,30,40,50],
		nowrap : true,
		border : false,
		idField : 'id',
		sortName : 'id',
		sortOrder : 'desc',
		view: sy.myview,
        emptyMsg: '没有查询到相关数据',
		toolbar: [
			{text:'增加',iconCls: 'icon-add',handler: addRow},'-',
			{text:'批量删除',iconCls: 'icon-remove',handler: deleteRow},'-',
			{text:'编辑',iconCls: 'icon-edit',handler: updateRow},'-',
			{text:'保存',iconCls: 'icon-save',handler: saveRow},'-',
			{text:'撤销',iconCls: 'icon-redo',handler: rejectRow},'-',
			{text:'刷新',iconCls: 'icon-reload',handler: function(){_datasDatagrid.datagrid('reload');}}
		],
		frozenColumns: [[
            {field:'id',title:'编号',align:'center',width:100,sortable:true,checkbox:true},
		]],
		columns:[[
            {field:'sendMsg',title:'接收消息',align:'left',width:100,sortable:true},
          	{field:'msgType',title:'返回类型',align:'left',width:100,sortable:true,
            	formatter:function(value, row) {
            		for ( var i = 0; i < jsonArr.length; i++) {
						if (value == jsonArr[i].code) {
							return jsonArr[i].name;
						}
					}
            	}
	        },
          	{field:'content',title:'返回内容',align:'left',width:100,sortable:true},
          	{field:'mediaId',title:'素材',align:'left',width:100,sortable:true},
          	{field:'title',title:'标题',align:'left',width:100,sortable:true},
          	{field:'description',title:'描述',align:'left',width:100,sortable:true},
          	{field:'musicUrl',title:'音乐地址',align:'left',width:100,sortable:true},
          	{field:'hQMusicUrl',title:'优质音乐地址',align:'left',width:100,sortable:true},
          	{field:'thumbMediaId',title:'缩略图',align:'left',width:100,sortable:true},
		]],
		onLoadSuccess : function(data) {
			editRowsNumber = -1;
			$.messager.progress('close');
		},
		onDblClickRow : function(rowIndex, rowData) {
			if (editRowsNumber != -1) {
				_datasDatagrid.datagrid('endEdit', editRowsNumber);
			} else {
				_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
				updateRow();
			}
		},
		onRowContextMenu : function(e, rowIndex, rowData){
			e.preventDefault();
			_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
			$('#datagridContextMenu').menu('show', {left:e.pageX,top:e.pageY});
		}
	});
});